package com.example.myapp.ADO;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.myapp.Activity.ArticleBody;
import com.example.myapp.Activity.Friendshome;
import com.example.myapp.Activity.Myhome;
import com.example.myapp.Activity.ShowArryImg;
import com.example.myapp.Model.Article;
import com.example.myapp.Model.Comment;
import com.example.myapp.Model.User;
import com.example.myapp.R;
import com.loopj.android.image.SmartImageView;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.datatype.BmobRelation;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import de.hdodenhof.circleimageview.CircleImageView;

public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
    private List<Article> Listpost;
    private Context context;


    private LayoutInflater mInflater;
    private List<String> listimgs = new ArrayList<String>();//创建图片url数组

    public PostAdapter(List<Article> Listpost, Context context) {
        this.Listpost = Listpost;
        this.context = context;
        this.mInflater = LayoutInflater.from(context);


    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        CircleImageView icon;
        TextView username;
        TextView artlist_time;
        TextView content;
        Button artlist_zan;
        TextView pageviewsnum;
        TextView artlist_zancount;
        Button artlist_zhuanfa;
        TextView artlist_zhuanfacount;
        TextView artlist_zhuanfakey;
        TextView artlist_zankey;
        TextView artlist_zhuanfapinlun;
        TextView listpinglun_count;
        LinearLayout artlist_body;
        LinearLayout homeitem;
        Button listpinglun_btn;
        HorizontalScrollView scll;
        LinearLayout ll;

        public ViewHolder(View view) {
            super(view);
            scll = view.findViewById(R.id.scll);
            ll = view.findViewById(R.id.ll);
            icon = view.findViewById(R.id.artlist_icon);
            artlist_time = view.findViewById(R.id.artlist_time);
            username = view.findViewById(R.id.artlist_username);
            content = view.findViewById(R.id.artlist_content);
            artlist_zan = view.findViewById(R.id.artlist_zan);
            artlist_zancount = view.findViewById(R.id.artlist_zancount);
            artlist_zhuanfa = view.findViewById(R.id.artlist_zhuanfa);
            artlist_zhuanfacount = view.findViewById(R.id.artlist_zhuanfacount);
            artlist_zhuanfakey = view.findViewById(R.id.artlist_zhuanfakey);
            artlist_zankey = view.findViewById(R.id.artlist_zankey);
            artlist_zhuanfapinlun = view.findViewById(R.id.artlist_zhuanfapinlun);
            listpinglun_count = view.findViewById(R.id.listpinglun_count);
            artlist_body = view.findViewById(R.id.artlist_body);
            homeitem = view.findViewById(R.id.homeitem);
            listpinglun_btn = view.findViewById(R.id.listpinglun_btn);
            pageviewsnum = view.findViewById(R.id.pageviewsnum);
        }

    }


    @Override

    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.articlelist, parent, false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final int i) {
        /**用户信息基本信息*/
        Glide.with(context).load(Listpost.get(i).getAuthor().getIcon().getUrl()).into(holder.icon);// CircleImageView.显示网络图片特殊方法
        holder.username.setText(Listpost.get(i).getAuthor().getUsername());
        holder.artlist_time.setText(Listpost.get(i).getCreatedAt());

        /**如果文章带转发品论的*/
        if (Listpost.get(i).getZhuanfaContent() != null) {
            holder.artlist_zhuanfapinlun.setVisibility(View.VISIBLE);
            holder.artlist_zhuanfapinlun.setText(Listpost.get(i).getZhuanfaContent());
            //content.setText(list.get(i).getContent());
            String[] split = Listpost.get(i).getContent().split(":");
            String str1 = "<font color = '#6795B5'>" + split[0] + ":" + "</font>" + split[1] + "";
            CharSequence charSequence;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                charSequence = Html.fromHtml(str1, Html.FROM_HTML_MODE_LEGACY);
            } else {
                charSequence = Html.fromHtml(str1);
            }
            holder.artlist_body.setBackgroundColor(Color.parseColor("#EEEEEE"));
            holder.content.setText(charSequence);
            /**如果文章是原著*/
        } else {
            holder.content.setText(Listpost.get(i).getContent());
        }
        /**转发、点赞、评论、浏览量*/

        holder.pageviewsnum.setText("" + Listpost.get(i).getPageviewNum().intValue());


        /**图片展示--横向浏览图片HorizontalScrollView*/
        listimgs = getlisturl(Listpost.get(i));//获取图片链接合成数组
        if (listimgs.size() == 0) {
            holder.scll.setVisibility(View.GONE);
        } else {
            /**--设置宽高*/
            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            double w = wm.getDefaultDisplay().getWidth() / 2.55; //获取屏幕宽度
            int with = Integer.parseInt(new java.text.DecimalFormat("0").format(w));
            LinearLayoutCompat.LayoutParams params = new LinearLayoutCompat.LayoutParams(with, LinearLayoutCompat.LayoutParams.WRAP_CONTENT);
            for (int j = 0; j < listimgs.size(); j++) {
                /**每个循环填充item_img_horizontal这个布局文件*/
                View v = mInflater.inflate(R.layout.item_img_horizontal, null);
                final SmartImageView imageView = v.findViewById(R.id.item_image);
                imageView.setId(j);
                imageView.setImageUrl(listimgs.get(j));
                final List<String> imgs = listimgs;
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(context, ShowArryImg.class);
                        intent.putExtra("postcontent", Listpost.get(i).getContent());
                        intent.putExtra("pathArry", imgs.toString());
                        intent.putExtra("index", imageView.getId() + "");
                        context.startActivity(intent);
                    }
                });
                holder.ll.addView(v, j, params);
            }

        }
        /**--处理该文章与当前用户是否有关联*/

        /**--是否转发*/
        BmobQuery<User> zhuanfa = new BmobQuery<User>();
        Article post2=new Article();
        post2.setObjectId(Listpost.get(i).getObjectId());
        zhuanfa.addWhereRelatedTo("zhuanfa", new BmobPointer(post2));
        zhuanfa.findObjects(new FindListener<User>() {
            @Override
            public void done(List<User> object, BmobException e) {
                if (e == null) {
                    holder.artlist_zhuanfacount.setText("" +object.size());
                    for (int i=0;i<object.size();i++){
                        //如果有自己
                        if (object.get(i).getObjectId().equals(BmobUser.getCurrentUser(User.class).getObjectId())){
                            holder. artlist_zhuanfa.setBackgroundResource(R.drawable.listzhuanfa1);
                             holder. artlist_zhuanfakey.setText("已转发");
                            return;
                        }
                    }
                } else {
                    Log.e("aaaa","查询转发失败"+ e.getMessage());
                }
            }
        });
        /**--转发按钮*/
      holder. artlist_zhuanfa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(!BmobUser.isLogin()){
                    Toast.makeText(context, "请登陆后再操作！", Toast.LENGTH_SHORT).show();
                    return;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                final EditText et =new EditText(context);
                builder.setView(et);
                builder.setTitle("说点什么吧");
                builder.setView(et);
                builder.setPositiveButton("转发",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                addzhuanfaflag(Listpost.get(i).getObjectId());
                                zhuanfa(Listpost.get(i).getObjectId(),Listpost.get(i).getAuthor().getUsername(),Listpost.get(i).getContent(),et.getText().toString(),Listpost.get(i));
                                Log.w("bmob","查询对象："+Listpost.get(i).getAuthor().getUsername());

                            }
                        });
                builder.setNegativeButton("取消",null);
                builder.show();
            }
        });


        /**是否点赞*/
        BmobQuery<User> query = new BmobQuery<User>();
        Article post = new Article();   // 创建需要查询的文章
        post.setObjectId(Listpost.get(i).getObjectId());
        //friend是User表中的字段，用来存储所有关注的用户
        query.addWhereRelatedTo("zan", new BmobPointer(post));
        query.findObjects(new FindListener<User>() {
            @Override
            public void done(List<User> object, BmobException e) {
                if (e == null) {
                    holder.artlist_zancount.setText("" +object.size());
                    for (int i=0;i<object.size();i++){
                   //如果有自己
                        if (object.get(i).getObjectId().equals(BmobUser.getCurrentUser(User.class).getObjectId())){
                            Log.w("aaaa", "我已经点赞了！"+object.get(i).getUsername());
                            holder.artlist_zan.setBackgroundResource(R.drawable.listdianzan1);
                            holder. artlist_zankey.setText("已点赞");
                            return;
                        }
                    }
                } else {
                    Log.e("aaaa","查询点赞失败"+ e.getMessage());
                }
            }
        });
        /**点赞按钮*/
        holder.  artlist_zan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!BmobUser.isLogin()){
                    Toast.makeText(context, "请登陆后再操作！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if ( holder.artlist_zankey.getText().toString().equals("已点赞")){
                    clearzan(Listpost.get(i).getObjectId(),Listpost.get(i).getZanNum().intValue(),i);
                }else {
                    addzan(Listpost.get(i).getObjectId(), Listpost.get(i).getZanNum().intValue(),i,Listpost.get(i).getPageviewNum().intValue());
                }

            }
        });



        /**初始化评论*/
        // 用此方式可以构造一个BmobPointer对象。只需要设置objectId就行
        BmobQuery<Comment> query_comment = new BmobQuery<>();
        Article post_comment = new Article();
        post_comment.setObjectId(Listpost.get(i).getObjectId());//测试文章1
        query_comment.addWhereEqualTo("article",new BmobPointer(post_comment));
        query_comment.include("user,author,article");
        query_comment.findObjects(new FindListener<Comment>() {
            @Override
            public void done(List<Comment> object, BmobException e) {
                if (e == null) {
                    Log.w("aaaa", "查询评论成功！"+object);
                  holder. listpinglun_count.setText(""+object.size());
                } else {
                    Log.e("aaaa","查询评论失败"+ e.getMessage());
                }
            }
        });

        /**评论按钮*/
        holder.  listpinglun_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!BmobUser.isLogin()){
                    Toast.makeText(context, "请登陆后再操作！", Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent(context,ArticleBody.class);
                Log.e("bbbb","我点到的文章id"+ Listpost.get(i).getObjectId()+"内容"+ Listpost.get(i).getContent());
                intent.putExtra("ArticleID", Listpost.get(i).getObjectId());
                context.startActivity(intent);
            }
        });

        /**点击文章主体*/
        holder.  homeitem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!BmobUser.isLogin()){
                    Toast.makeText(context, "请登陆后再操作！", Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent(context, ArticleBody.class);
                Log.e("bbbb","我点到的文章id"+ Listpost.get(i).getObjectId()+"内容"+ Listpost.get(i).getContent());
                intent.putExtra("ArticleID", Listpost.get(i).getObjectId());
                context.startActivity(intent);
            }
        });


       holder. icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!BmobUser.isLogin()){
                    Toast.makeText(context, "请登陆后再操作！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if ( Listpost.get(i).getAuthor().getObjectId().equals(BmobUser.getCurrentUser(User.class).getObjectId())){
                    Intent intent = new Intent(context, Myhome.class);
                    context.startActivity(intent);
                }else {
                    Intent intent = new Intent(context, Friendshome.class);
                    intent.putExtra("userID", Listpost.get(i).getAuthor().getObjectId());
                    intent.putExtra("iconUrl",Listpost.get(i).getAuthor().getIcon().getUrl());
                    intent.putExtra("userName",Listpost.get(i).getAuthor().getUsername());
                    if (Listpost.get(i).getAuthor().getShow()!=null){
                        intent.putExtra("jianJie",Listpost.get(i).getAuthor().getShow());
                    }
                    context.startActivity(intent);
                }

            }
        });




        holder. username.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!BmobUser.isLogin()){
                    Toast.makeText(context, "请登陆后再操作！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if ( Listpost.get(i).getAuthor().getObjectId().equals(BmobUser.getCurrentUser(User.class).getObjectId())){
                    Intent intent = new Intent(context, Myhome.class);
                    context.startActivity(intent);
                }else {
                    Intent intent = new Intent(context, Friendshome.class);
                    intent.putExtra("userID", Listpost.get(i).getAuthor().getObjectId());
                    intent.putExtra("iconUrl",Listpost.get(i).getAuthor().getIcon().getUrl());
                    intent.putExtra("userName",Listpost.get(i).getAuthor().getUsername());
                    if (Listpost.get(i).getAuthor().getShow()!=null){
                        intent.putExtra("jianJie",Listpost.get(i).getAuthor().getShow());
                    }
                    context.startActivity(intent);
                }

            }
        });







    }

    //填写被当前用户要关注的用户id
    private void addzhuanfaflag(String userObjId) {

        if (BmobUser.isLogin()) {
            Log.i("aaaa", "已经登陆："+BmobUser.getCurrentUser(User.class));
            User user = BmobUser.getCurrentUser(User.class);
            Article article = new Article();//创建被点赞的文章并且给上Id
            article.setObjectId(userObjId);
            //将当前用户添加到Post表中的likes字段值中，表明当前用户喜欢该帖子
            BmobRelation relation = new BmobRelation();//创建多对多关联容器
            //将当前用户添加到多对多关联中
            relation.add(user);//装进去当前用户;
            article.setZhuanfa(relation);
            article.update(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        Log.i("aaaa", "添加转发成功");

                    } else {
                        Log.i("aaaa", "添加转发失败：" + e.getMessage());
                    }
                }
            });

        }else {
            Log.i("aaaa", "请先登录");
        }
    }


    /**添加多对多文章转发*/
    private void zhuanfa(String articleId, String articleAuthor, String content, String input, Article article){

        Article zhuanfa=new Article();
        zhuanfa.setZhuanfaContent(input);
        zhuanfa.setContent("@"+articleAuthor+":"+content);
        if (article.getImages()!=null){
            zhuanfa.setImages(article.getImages());
        }
        if (article.getImages2()!=null){
            zhuanfa.setImages2(article.getImages2());
        }
        if (article.getImages3()!=null){
            zhuanfa.setImages3(article.getImages3());
        }
        if (article.getImages4()!=null){
            zhuanfa.setImages4(article.getImages4());
        }
        if (article.getImages5()!=null){
            zhuanfa.setImages5(article.getImages5());
        }
        if (article.getImages6()!=null){
            zhuanfa.setImages6(article.getImages6());
        }
        zhuanfa.setPageviewNum(0);//访客记录
        zhuanfa.setZanNum(0);
        zhuanfa.setPinlunNum(0);
        zhuanfa.setLikeNum(0);
        zhuanfa.setZhuanfaNum(0);
        zhuanfa.setOrderTime(System.currentTimeMillis());
        //添加一对一关联，用户关联帖子
        zhuanfa.setAuthor(BmobUser.getCurrentUser(User.class));
        zhuanfa.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    Log.w("aaaa", "转发帖子成功！" + s);
                    saveComment(articleId,input);
                    Toast.makeText(context,"转发成功" , Toast.LENGTH_LONG).show();

                } else {
                    Log.w("aaaa", "转发帖子失败！" + e.getMessage());
                    Toast.makeText(context,"转发失败" , Toast.LENGTH_LONG).show();
                    notifyDataSetChanged();//重新加载listview数据卡了我半天
                }
            }
        });

    }//不带照片的

    /**添加多对多文添加评论*/
    private void saveComment( String articlrId ,String pinlun) {
        Article post = new Article();
        post.setObjectId(articlrId);//测试文本1的文章id
        User user = BmobUser.getCurrentUser(User.class);
        final Comment comment = new Comment();

        comment.setContent(pinlun);
        comment.setArticle(post);//上传文章ID
        comment.setAuthor(user);//上传当前作者名字
        comment.save(new SaveListener<String>() {
            @Override
            public void done(String objectId, BmobException e) {
                if (e == null) {
                    Log.i("bmob", "评论发表成功");
                } else {
                    Log.i("bmob", "评论发表失败：" + e.getMessage());
                }
            }
        });
    }


    /** 删除多对多*/
    //填写被当前用户要关注的用户id
    private void clearzan(String articleObjId,int num,int psition) {

        if (BmobUser.isLogin()) {
            Log.i("aaaa", "已经登陆："+BmobUser.getCurrentUser(User.class));
            User user = BmobUser.getCurrentUser(User.class);
            Article article = new Article();//创建被关注用户并且给上Id
            article.setObjectId(articleObjId);
            //将当前用户添加到Post表中的likes字段值中，表明当前用户喜欢该帖子
            BmobRelation relation = new BmobRelation();//创建多对多关联容器
            //将当前用户添加到多对多关联中
            relation.remove(user);//装进去当前用户;
            article.setZan(relation);
            num--;
            article.setZanNum(num);
            article.update(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        Log.i("aaaa", "取消点赞成功");
                        notifyItemChanged(psition);
                    } else {
                        Log.i("aaaa", "取消点赞失败：" + e.getMessage());

                    }
                }
            });

        }else {
            Log.i("aaaa", "请先登录");
        }
    }
    /**添加多对多文章关注*/
    //填写被当前用户要关注的用户id
    private void addzan(String userObjId ,int num, int psition,int pageviews) {

        if (BmobUser.isLogin()) {
            Log.i("aaaa", "已经登陆："+BmobUser.getCurrentUser(User.class));
            User user = BmobUser.getCurrentUser(User.class);
            Article article = new Article();//创建被点赞的文章并且给上Id
            article.setObjectId(userObjId);
            //将当前用户添加到Post表中的likes字段值中，表明当前用户喜欢该帖子
            BmobRelation relation = new BmobRelation();//创建多对多关联容器
            //将当前用户添加到多对多关联中
            relation.add(user);//装进去当前用户;
            article.setZan(relation);
            pageviews++;
            num++;
            article.setZanNum(pageviews);
            article.setPageviewNum(pageviews);
            article.update(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        Log.i("aaaa", "添加点赞成功");
//                        notifyDataSetChanged();//重新加载listview数据卡了我半天
                      notifyItemChanged(psition);
                    } else {
                        Log.i("aaaa", "添加点失败：" + e.getMessage());
                    }
                }
            });

        }else {
            Log.i("aaaa", "请先登录");
        }
    }
















    //    获取图片数组
    private List<String> getlisturl(Article posts){
        List<String> urlList=new ArrayList<>();
        if(posts.getImages()!=null){
            urlList.add(posts.getImages().getUrl());
        }
        if(posts.getImages2()!=null){
            urlList.add(posts.getImages2().getFileUrl());
        }
        if(posts.getImages3()!=null){
            urlList.add(posts.getImages3().getFileUrl());
        }
        if(posts.getImages4()!=null){
            urlList.add(posts.getImages4().getFileUrl());
        }
        if(posts.getImages5()!=null){
            urlList.add(posts.getImages5().getFileUrl());
        }
        if(posts.getImages6()!=null){
            urlList.add(posts.getImages6().getFileUrl());
        }

        return urlList;

    }



    @Override
    public int getItemCount(){
        return Listpost.size();
    }
}
